--- title: Removing Pesky Background Objects with Image Stacking in Python author: '' date: '2020-10-05' slug: image-stacking-python categories: [] tags: - python - projects - image processing description: '' repo: '' weight: 0 ---
We’ve all probably at some point intended to take a picture of someone or something, only to have our shot photobombed by another object of person. Or maybe we’re recording a video and that happens. Fortunately we have Photoshop and an array of other tools at our disposal, but let’s use Python to see how image stacking can remove unwanted objects from a set of images to produce a single image with the desired object. Another challenge project from Lee Vaughan’s book Impractical Python Projects, this time from Chapter 15.
I have 8 images that contain a toy train that you can pretend is chugging along on a desk based on its position in various frames. Here’s what the images look like.

Figure 1: Various images of a toy train passing through
The goal is to produce a single image that consists only of the background – that is, the desk. This should be the final outcome:

Figure 2: The outcome after stacking the 8 images above to remove the toy train
Of course, this is a bit silly of an example, but the image stacking in this project can be used for more real-world purposes, like removing unwanted tourists from your vacation pics. The principle will be the same, and that is discussed next.
How would you remove an unwanted something from your images by stacking. One of the assumptions is that the background is constant, the only thing moving being the pesky object (maybe a fly). By capturing the RGB (red, green, blue) contents for each pixel and image, we can then take the median across images so that the unwanted object’s RGB gets pushed out.

Figure 3: Stacking images then taking the median across images to remove the black pixel. Source: Impractical Python Projects, p. 344
In Figure 3 we have five images, and we’re looking at the RGB for a particular pixel location. By taking the median of the red, green, and blue pixel densities, we arrive at the final image at the bottom with the blackened pixel removed.